package ran.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ran.api.RemoteJudgeService;
import ran.api.domain.dto.JudgeSubmitDTO;
import ran.api.domain.vo.UserQuestionResultVO;
import ran.constants.Constants;
import ran.entity.Result;
import ran.enums.ProgramType;
import ran.enums.ResultCode;
import ran.exception.ServiceException;
import ran.friend.domain.question.entity.Question;
import ran.friend.domain.question.entity.QuestionCase;
import ran.friend.domain.question.es.QuestionES;
import ran.friend.domain.user.dto.UserSubmitDTO;
import ran.friend.elsticsearch.QuestionRepository;
import ran.friend.mapper.question.QuestionMapper;
import ran.friend.rabbitmq.JudgeProducer;
import ran.friend.service.user.IUserQuestionService;
import ran.utils.ThreadLocalUtil;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-11-22
 * Time: 16:35
 */
@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private JudgeProducer judgeProducer; // 引入生产者

    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 处理Java代码
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitmqSubmit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 处理Java代码
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        Long questionId = userSubmitDTO.getQuestionId();
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        // 先从ES查询
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        if (questionES != null) {
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);
        }else {
            Question question = questionMapper.selectById(questionId);
            if (question == null) {
                throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
            }
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            // 刷新缓存
            questionES = new QuestionES();
            BeanUtil.copyProperties(question,questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(assembleContent(questionES.getMainFuc(),userSubmitDTO.getUserCode()));
        // 封装输入测试用例
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(inputList);
        // 封装输出测试用例
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;

    }
    // 拼接main函数和用户的代码
    private String assembleContent(String mainFuc, String userCode) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFuc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }

}






























